package fun.rockchen.service.concreteService;

import fun.rockchen.bean.AddTaskEntity;
import fun.rockchen.bean.MapTaskEntity;
import fun.rockchen.bean.Task;
import fun.rockchen.bean.TaskTimeEntity;
import fun.rockchen.dao.TaskDao;
import fun.rockchen.service.interfaceService.TaskService;
import fun.rockchen.utils.responseUtils.ResponseJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Rock Chen
 * @Description:
 * @date 2023/10/16 11:32
 */

@Service
public class TaskServiceImpl implements TaskService {
    private final TaskDao taskDao;

    @Autowired
    public TaskServiceImpl(TaskDao taskDao) {
        this.taskDao = taskDao;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackForClassName = "Exception")
    public ResponseEntity<?> addTask(AddTaskEntity addTaskEntity) {
        try {
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = addTaskEntity.getStartTime();
            Date date;
            date = format1.parse(time);
            String startTime = format1.format(date);
            addTaskEntity.setStartTime(startTime);
            List<Task> taskList = taskDao.getTaskByStartTime(addTaskEntity.getUserId(), addTaskEntity.getStartTime());
            if (!taskList.isEmpty()) {
                return ResponseEntity.ok(ResponseJson.TaskExist());
            }

            String id = UUID.randomUUID().toString().replace("-", "");
            addTaskEntity.setId(id);
            boolean addTaskFlag = taskDao.addTask(addTaskEntity);
            if (addTaskFlag) {
                boolean addUserTaskFlag = taskDao.addUserMapTask(addTaskEntity);
                if (addUserTaskFlag) {
                    List<String> tagList = addTaskEntity.getTagList();
                    for (String tag : tagList) {
                        taskDao.addTaskMapTag(addTaskEntity.getId(), tag);
                    }
                    return ResponseEntity.ok().body(ResponseJson.insertSuccess());
                }
            }
            return ResponseEntity.status(488).body(ResponseJson.insertFail());
        } catch (Exception e) {
            //手动提交事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseEntity.status(488).body(ResponseJson.insertFail());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackForClassName = "Exception")
    public ResponseEntity<?> deleteTask(String taskId) {
        try {
            boolean flag = taskDao.deleteTaskStep1(taskId);
            if (flag) {
                boolean flag1 = taskDao.deleteTaskStep2(taskId);
                if (flag1) {
                    return ResponseEntity.ok().body(ResponseJson.deleteSuccess());
                }
            }
            return ResponseEntity.status(498).body(ResponseJson.deleteFail());
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseEntity.status(498).body(ResponseJson.deleteFail());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackForClassName = "Exception")
    public ResponseEntity<?> updateTask(Task task) {
        try {
            boolean flag = taskDao.updateTask(task);
            if (flag) {
                List<String> tagList = task.getTagList();
                // 修改task的tag
                taskDao.updateTaskTagStep1(task.getId());
                for (String tag : tagList) {
                    task.setTagId(tag);
                    taskDao.updateTaskTagStep2(task);
                }
                return ResponseEntity.ok().body(ResponseJson.updateSuccess());
            } else {
                return ResponseEntity.status(499).body(ResponseJson.updateFail());
            }
        } catch (Exception e) {
            //手动提交事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseEntity.status(496).body(ResponseJson.fail());
        }
    }

    @Override
    public ResponseEntity<?> getStatusTask(MapTaskEntity mapTaskEntity) {
        List<Task> taskList = taskDao.getStatusTask(mapTaskEntity);
        if (taskList.isEmpty()) {
            return ResponseEntity.ok().body(ResponseJson.NoData());
        }
        return ResponseEntity.ok().body(ResponseJson.getSuccess(taskList));
    }

    @Override
    public ResponseEntity<?> getTodayTask(MapTaskEntity mapTaskEntity) {
        List<Task> taskList = taskDao.getTaskByTime(mapTaskEntity);
        if (taskList.isEmpty()) {
            return ResponseEntity.ok().body(ResponseJson.NoData());
        }
        return ResponseEntity.ok().body(ResponseJson.getSuccess(taskList));
    }

    @Override
    public ResponseEntity<?> getTaskByTime(MapTaskEntity mapTaskEntity) throws ParseException {
        // 将获取到的所有task根据时间段进行分类
        List<Task> taskList = taskDao.getTaskByTime(mapTaskEntity);
        // 定义一个list
        Map<String, List<Task>> map = new HashMap<>();
        for (int i = 0; i < 24; i++) {
            map.put(String.format("%02d", i), new ArrayList<>());
        }
        for (Task task : taskList) {
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(task.getStartTime());
            String newString = new SimpleDateFormat("HH").format(date);
            if (map.containsKey(newString)) {
                map.get(newString).add(task);
            }
        }
        return ResponseEntity.ok().body(ResponseJson.success(map));
    }

    @Override
    public ResponseEntity<?> getTaskByState(MapTaskEntity mapTaskEntity) {
        List<Task> taskList = taskDao.getTaskByState(mapTaskEntity);
        if (taskList.isEmpty()) {
            return ResponseEntity.ok().body(ResponseJson.NoData());
        }
        return ResponseEntity.ok().body(ResponseJson.getSuccess(taskList));
    }

    @Override
    public ResponseEntity<?> getTaskById(String id) {
        Task task = taskDao.getTaskById(id);
        if (task == null) {
            return ResponseEntity.ok().body(ResponseJson.NoData());
        }
        return ResponseEntity.ok().body(ResponseJson.getSuccess(task));
    }

    @Override
    public ResponseEntity<?> changeTaskIntoCancel(MapTaskEntity mapTaskEntity) {
        System.out.println(mapTaskEntity.getId());
        boolean flag = taskDao.changeTaskIntoCancel(mapTaskEntity);
        if (flag) {
            return ResponseEntity.ok().body(ResponseJson.updateSuccess());
        }
        return ResponseEntity.status(4588).body(ResponseJson.updateFail());
    }

    @Override
    public ResponseEntity<?> changeTaskIntoPending(MapTaskEntity mapTaskEntity) {
        boolean flag = taskDao.changeTaskIntoPending(mapTaskEntity);
        if (flag) {
            return ResponseEntity.ok().body(ResponseJson.updateSuccess());
        } else {
            return ResponseEntity.status(4988).body(ResponseJson.updateFail());
        }
    }

    @Override
    public ResponseEntity<?> getTaskByDate(MapTaskEntity mapTaskEntity) {
        String time = (String) mapTaskEntity.getOptions();
        String[] list = time.split("-");
        String dateFormat = list[0] + "-" + list[1];
        mapTaskEntity.setOptions(dateFormat);
        List<String> dateList = taskDao.getTimeByDate(mapTaskEntity);
        Map<String, List<Task>> map = new LinkedHashMap<>();
        List<Task> taskList;
        // 循环dateList，发请求获取对应日期的task，然后组成json数据
        for (String date : dateList) {
            mapTaskEntity.setOptions(date);
            taskList = taskDao.getTaskByDate(mapTaskEntity);
            if (!taskList.isEmpty()) {
                map.put(date, taskList);
            }
        }
        return ResponseEntity.ok().body(ResponseJson.getSuccess(map));
    }

    @Override
    public ResponseEntity<?> getTaskTotalTime(TaskTimeEntity taskTimeEntity) {
        SimpleDateFormat timeFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String time = taskTimeEntity.getStartTime();
        Date date;
        try {
            date = timeFormat1.parse(time);
            String startTime = timeFormat1.format(date);
            taskTimeEntity.setStartTime(startTime);
            long second = taskDao.getTaskTotalTime(taskTimeEntity);
            long hours = TimeUnit.SECONDS.toHours(second);
            long minutes = TimeUnit.SECONDS.toMinutes(second) - TimeUnit.HOURS.toMinutes(hours);
            Map<String, Long> map = new HashMap<>();
            map.put("hours", hours);
            map.put("minutes", minutes);
            return ResponseEntity.ok(ResponseJson.getSuccess(map));
        } catch (Exception e) {
            return ResponseEntity.ok(ResponseJson.getError());
        }
    }
}
